package com.example.android.contactmanager;

import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public final class ContactList extends Activity
{
    public static final String TAG = "ContactManager";

    private ListView contactList;
    private Cursor cursor;
    private int selectedPosition;
    private long selectedId;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Log.v(TAG, "Activity State: onCreate()");
        
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.contact_list);

        contactList = (ListView) findViewById(R.id.contactList);

        contactList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
            		int position, long id) {
            	selectedPosition = position;
            	selectedId = id;
            	
            	showDialog(0);
            }
          });        

        // Populate the contact list
        populateContactList();
    }

    private void populateContactList() {
        // Build adapter with contact entries
    	cursor = getContacts();
        
        String[] from = new String[] {
        		ContactsContract.Data.TIMES_CONTACTED,
        		ContactsContract.Contacts.DISPLAY_NAME
        };
        int[] to = {
        		R.id.contactEntryTimesContacted,
        		R.id.contactEntryFullname
        };
        
        AdapterList adapter = new AdapterList(this, R.layout.contact_entry,
        		cursor, from, to);
        
        contactList.setAdapter(adapter);
    }

    private Cursor getContacts()
    {
        // Run query
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        
        String[] projection = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Data.TIMES_CONTACTED,
                ContactsContract.Contacts.HAS_PHONE_NUMBER
        };
        
        String selection = "";
        String[] selectionArgs = null;
        
        String sortOrder = ContactsContract.Data.TIMES_CONTACTED + " DESC, " +
        		ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
    }
    
    protected Dialog onCreateDialog(int view) {
    	Dialog dialog = null;
    	ContactDetail.Builder contactDetail = new ContactDetail.Builder(this);
	    
		dialog = contactDetail.create();
		
		return dialog;
    }
    
    protected void onPrepareDialog(int id, Dialog dialog) {
    	Cursor cur;
    	
	    cursor.moveToPosition(selectedPosition);
        int colDisplayName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        int colHasNumber = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        
        // Display name
        String displayName = cursor.getString(colDisplayName);
        int hasNumber = cursor.getInt(colHasNumber);
        ((ContactDetail)dialog).setDisplayName(displayName);
        
        // Phone number
        if(hasNumber == 1)
        {
			cur = getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
					null, 
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", 
					new String[]{String.valueOf(selectedId)},
					null
			);
			
			cur.moveToFirst();
			
			int colNumber = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
			String number = cur.getString(colNumber);
			
			cur.close();
			
        	((ContactDetail)dialog).setNumber(number);
        }
        else
        	((ContactDetail)dialog).setNumber("");

        // Phone number
		cur = getContentResolver().query(
				ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
				null, 
				ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
				new String[]{String.valueOf(selectedId)},
				null
		);
		
		if(cur.getCount() > 0)
		{
			cur.moveToFirst();
			
			int colEmail = cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
			String email = cur.getString(colEmail);
			
			cur.close();
			
	    	((ContactDetail)dialog).setEmail(email);
		}
    	else
        	((ContactDetail)dialog).setEmail("");        
        
        // Contact ID to be able to get the picture later in the Dialog
        // Didn't make it to copy the bitmap from the contact_entry to
        // the contact_detail ImageView. 
        ((ContactDetail)dialog).setId(selectedId);
    }
}
